package com.whmnx.shop.ui.viewmodel;

import android.app.Application;
import android.view.View;
import android.widget.CompoundButton;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.classic.adapter.CommonRecyclerAdapter;
import com.whmnx.base.bean.LoginBean;
import com.whmnx.base.bean.ShoppingBean;
import com.whmnx.base.constants.Constants;
import com.whmnx.base.http.CallBack;
import com.whmnx.base.http.HttpClient;
import com.whmnx.base.router.RouterActivityPath;
import com.whmnx.shop.BR;
import com.whmnx.shop.R;
import com.whmnx.shop.databinding.FragmentShoppingBinding;
import com.whmnx.shop.ui.adapter.ShopListAdapter;
import com.whmnx.shop.ui.fragment.ShoppingFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

/**
 * author : huang
 * date   : 2020/9/21 0021 14:51
 * version: 1.0
 * @author Administrator
 */
public class ShoppingModel extends ToolbarViewModel {

    private ShopListAdapter shopListAdapter;

    public ShoppingModel(@NonNull Application application) {
        super(application);
    }

    private FragmentShoppingBinding mBinding;
    private ShoppingFragment mFragment;
    private boolean isEdit;
    private boolean isAll;

    private int page = 1;
    private int pageSize = 10;

    public void initToolbar(ShoppingFragment shoppingFragment, FragmentShoppingBinding binding) {
        this.mBinding = binding;
        this.mFragment = shoppingFragment;
        setTitleText("购物车");
        setRightText("编辑");
        setRightTextVisible(View.VISIBLE);
        setLeftIconSetVisible(View.INVISIBLE);
        initView();
        initListener();
    }



    public void initView() {
        mBinding.rvGoodsList.setLayoutManager(new LinearLayoutManager(mFragment.getActivity()));
        mBinding.rvGoodsList.setItemAnimator(null);
        shopListAdapter = new ShopListAdapter(mFragment.getActivity());
        mBinding.rvGoodsList.setAdapter(shopListAdapter);
        addShopcart(true);
        mBinding.refresh.setOnRefreshListener(refreshLayout -> addShopcart(true));
          mBinding.refresh.setOnLoadMoreListener(refreshLayout -> addShopcart(false));

        shopListAdapter.setOnItemClickListener(new CommonRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int i) {
                SPUtils.getInstance().put("Product_Id", shopListAdapter.getItem(i).getShopCart_ProductId());
                ARouter.getInstance().build(RouterActivityPath.Main.ORDER).navigation();
            }
        });
    }


    private void addShopcart(final boolean isRefresh) {
        if (isRefresh) page = 1;
        Map<String, Object> params = new HashMap<>();
        params.put("userInfo_Id", SPUtils.getInstance().getString(Constants.USERID));
        params.put("pageIndex", page);
        params.put("pageSize", pageSize);

        HttpClient.post(mFragment.getActivity(), Constants.SELSHOPCART, params,new CallBack<List<ShoppingBean>>() {
            @Override
            public void onSuccess(List<ShoppingBean> shoppingBeans) {
                isAll = false;
                shopListAdapter.allSelect(false);
                if (isRefresh){
                    mBinding.refresh.finishRefresh(true);
                    shopListAdapter.replaceAll(shoppingBeans,true);
                    if (shoppingBeans.size() == 0){
                        mBinding.llEmpty.setVisibility(View.VISIBLE);
                        mBinding.refresh.setVisibility(View.GONE);
                    }else {
                        mBinding.llEmpty.setVisibility(View.GONE);
                        mBinding.refresh.setVisibility(View.VISIBLE);
                    }
                }else {
                    if (shoppingBeans.size() > 0) {
                        mBinding.refresh.finishLoadMore(true);
                        shopListAdapter.addAll(shoppingBeans);
                    } else {
                        mBinding.refresh.finishLoadMoreWithNoMoreData();
                    }
                }
                page++;
            }
        });
    }

    //给RecyclerView添加ObservableList
    public ObservableList<ShoppingItemViewModel> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<ShoppingItemViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_shop);

    //结算(下单)
    public BindingCommand jieOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Map<String, Object> params = new HashMap<>();
            ArrayList<String> list = new ArrayList<>();
            for (ShoppingBean shoppingBean : shopListAdapter.getData()) {
                if (shoppingBean.isSelect()){
                    list.add(shoppingBean.getShopCart_Id());
                }
            }

            if (list.size() == 0){
                ToastUtils.showShort("请先选择商品");
                return;
            }

           // ARouter.getInstance().build(RouterActivityPath.Main.ORDER).navigation();
         //   Bundle bundle =  new Bundle();
          //  bundle.putStringArrayList("list",list);
            Constants.list = list;
            Constants.ORDERBEAN = null;
            ARouter.getInstance().build(RouterActivityPath.Home.COM).navigation();

          //  startActivity(ConfirmOrderActivity2.class,bundle);

         //   params.put("ids",list);

         //   params.put("userInfo_Id",SPUtils.getInstance().getString(Constants.USERID));

           /* HttpClient.post(Utils.getContext(), Constants.SHOPCARTORDER, params,new CallBack<OrderBean>() {
                @Override
                public void onSuccess(OrderBean result) {


                }
            });*/
        }
    });

    //删除
    public BindingCommand celOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Map<String, Object> params = new HashMap<>();
            List<String> list = new ArrayList<>();
            for (ShoppingBean shoppingBean : shopListAdapter.getData()) {
                if (shoppingBean.isSelect()){
                    list.add(shoppingBean.getShopCart_Id());
                }
            }

            if (list.size() == 0){
                ToastUtils.showShort("请先选择商品");
                return;
            }
            params.put("",list);
            HttpClient.post(mFragment.getActivity(), Constants.DELSHOPCART, params,new CallBack<LoginBean>() {
                @Override
                public void onSuccess(LoginBean result) {
                    addShopcart(true);
                }
            });
        }
    });

    //收藏
    public BindingCommand colOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Map<String, Object> params = new HashMap<>();
            List<String> list = new ArrayList<>();
            for (ShoppingBean shoppingBean : shopListAdapter.getData()) {
                if (shoppingBean.isSelect()){
                    list.add(shoppingBean.getShopCart_Id());
                }
            }
            if (list.size() == 0){
                ToastUtils.showShort("请先选择商品");
                return;
            }
            params.put("",list);
            HttpClient.post(mFragment.getActivity(), Constants.DELSHOPCART, params,new CallBack<LoginBean>() {
                @Override
                public void onSuccess(LoginBean result) {

                }
            });
        }
    });

    //全选
   /* public BindingCommand allOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            //全选
            if (!isAll) {
                isAll = true;
                mBinding.tvAllSelect.setChecked(true);
                shopListAdapter.allSelect(true);
            } else {
                isAll = false;
                mBinding.tvAllSelect.setChecked(false);
                shopListAdapter.allSelect(false);
            }
            heji2();
        }
    });*/

    /**
     * 合计
     */
    private void heji2() {
        double num = 0;
        int zS = 0;
        for (ShoppingBean shoppingBean : shopListAdapter.getData()) {
             if (shoppingBean.isSelect()){
                 num += shoppingBean.getShopCart_SPECMoney() * (double) shoppingBean.getShopCart_Num();
                 zS += shoppingBean.getShopCart_Num();
             }
        }

        mBinding.tvMoeny.setText(num + "");
        mBinding.tvAllSelect.setText("全选("  + zS + ")");
    }

    /**
     * 编辑
     */
    @Override
    protected void rightTextOnClick() {
        if (shopListAdapter != null) {
            if (isEdit) {
                isEdit = false;
                setRightText("编辑");
                shopListAdapter.setEdit(false);
                mBinding.tvJie.setVisibility(View.VISIBLE);
                mBinding.tvCel.setVisibility(View.GONE);
                mBinding.tvCollect.setVisibility(View.GONE);
            } else {
                isEdit = true;
                setRightText("完成");
                shopListAdapter.setEdit(true);
                mBinding.tvJie.setVisibility(View.GONE);
                mBinding.tvCel.setVisibility(View.VISIBLE);
                mBinding.tvCollect.setVisibility(View.GONE);
            }
        }
    }


    private void initListener() {
           mBinding.tvAllSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    //全选
                    isAll = true;
                    mBinding.tvAllSelect.setChecked(true);
                    shopListAdapter.allSelect(true);
                }else {
                    isAll = false;
                    mBinding.tvAllSelect.setChecked(false);
                    shopListAdapter.allSelect(false);
                }
            }
        });

       shopListAdapter.setOnEditCall(new ShopListAdapter.OnEditCall() {
            @Override
            public void collection(String goodsId) {
                List<String> list = new ArrayList<>();
                list.add(goodsId);
            }

            @Override
            public void updateSpec(int fposition, int position, String carId, String goodsId) {

            }

            @Override
            public void heji() {
                //合计后修改价格
                heji2();
            }

            @Override
            public void isAll() {
                //改变全选按钮
                if (issAll()) {
                    mBinding.tvAllSelect.setChecked(true);
                } else {
                    mBinding.tvAllSelect.setChecked(false);
                }
            }

            @Override
            public void sonSelect(int position) {
             //  shopListAdapter.setSelect(position, true);
            }

            @Override
            public void updateData() {

            }
        });
    }


    //是否全选
    private boolean issAll() {
        boolean isAll = false;
        for (ShoppingBean shopCarBean : shopListAdapter.getData()) {
            if (shopCarBean.isSelect()) {
                isAll = true;
            } else {
                return false;
            }
        }
        return isAll;
    }
}
